﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using UserService.DataAccessService;

namespace UserService
{
    class UserService :IUserService
    {
        private static readonly Uri DataAccessAddress = new Uri("http://localhost:3151/DataAccess.svc");
        private SiteXtenderEntities dataAccessService = new SiteXtenderEntities(DataAccessAddress);

        public User GetById(int id)
        {
            Program.logService.Trace(@"""Get user by id"" invoked");
            User result = null;
            try
            {
                result = dataAccessService.UserSet.Where(u => u.Id == id).First();
            }
            catch (Exception)
            {
                Program.logService.Error("DataAccessService error!");
            }
            return result;
        }

        public User GetByLogin(string login)
        {
            Program.logService.Trace(@"""Get user by login"" invoked");
            User result = null;
            try
            {
                result = dataAccessService.UserSet.Where(u => u.Login == login).First();
            }
            catch (Exception)
            {
                Program.logService.Error("DataAccessService error!");
            }
            return result;
        }

        public void Add(User user)
        {
            Program.logService.Trace(@"""Add user"" invoked");
            dataAccessService.AddToUserSet(user);
            try
            {
                dataAccessService.SaveChanges();
            }
            catch (Exception)
            {
                Program.logService.Error("DataAccessService error!");
                throw new FaultException("DataAccessService error!");
            }
        }

        public User GetByMessageId(int id)
        {
            Program.logService.Trace(@"""Get user by Message Id"" invoked");
            User u = null;
            try
            {
                u = dataAccessService.MessageSet.Where(m => m.Id == 1).Select(m => m.User).First();dataAccessService.MessageSet.Where(m => m.Id == 1).Select(m => m.User).First();
            }
            catch (Exception)
            {
                Program.logService.Error("DataAccessService error!");
            }
            return u;
        }
    }
}
